package com.pgy.general.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pgy.general.annotation.PassToken;
import com.pgy.general.entity.Document;
import com.pgy.general.entity.User;
import com.pgy.general.mapper.UserMapper;
import com.pgy.general.result.RetCode;
import com.pgy.general.result.RetResponse;
import com.pgy.general.result.RetResult;
import com.pgy.general.service.IUserService;
import com.pgy.general.util.FileUtil;
import com.pgy.general.util.PathUtil;
import com.pgy.general.util.TokenUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.w3c.dom.stylesheets.LinkStyle;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Cc
 * @since 2021-01-26
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户接口")
public class UserController {
    @Autowired
    private IUserService iUserService;
    @Autowired
    private UserMapper userMapper;
    //登录接口，添加该注解跳过token验证
    @PassToken
    @ApiOperation(value = "/login", notes = "用户登录（只传用户名和密码参数即可）,用接口测试前请先登录（缓存用户信息）", httpMethod = "GET")
    @GetMapping("/login")
    public RetResult login(String username,String password,HttpServletRequest httpServletRequest) {
        Map<String,Object> map=new HashMap<>();
//        User user=new User();
//        user.setUsername(username);
//        user.setPassword(password);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userName", username).eq("password",password);
        queryWrapper.isNull("deleteTime");
        User user1 = userMapper.selectOne(queryWrapper);
        if(user1 != null){
            String token = TokenUtil.getToken(user1,httpServletRequest);
            map.put("user",user1);
            map.put("token",token);
            return RetResponse.makeOKRsp(RetCode.SUCCESS,map,"登陆成功！");
        }else{
            return RetResponse.makeErrRsp("登录失败,用户名或密码错误！");
        }
    }

    //添加对象
    @PostMapping("/add")
    @ApiOperation(value = "管理员添加/修改用户接口",notes = "不传输id时管理员为添加用户，传输id时为修改指定用户信息(level不用传递)",httpMethod = "POST")
    public RetResult addStudent(@Validated User user, HttpServletRequest request) {
        user.setLevel(0);
        user.setCreateTime(new Date());
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userName",user.getUsername());
        queryWrapper.isNull("deleteTime");
        User user1 = userMapper.selectOne(queryWrapper);
        if(user.getId() == null){
            if (user1 == null){
                iUserService.save(user);
                return RetResponse.makeOKRsp();
            }else {
                return RetResponse.makeErrRsp("该用户名已被注册，请更换用户名重新注册");
            }
        }
        else {
            iUserService.updateById(user);
            return RetResponse.makeOKRsp();
        }
    }


    @PassToken
    @PostMapping("/updateUserPassword")
    @ApiOperation(value = "忘记密码", notes = "重置用户密码接口",httpMethod = "POST")
    public RetResult updateManager(String userName, HttpServletRequest request) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userName",userName);
        queryWrapper.isNull("deleteTime");
        User user1 = userMapper.selectOne(queryWrapper);
        if (user1 != null){
            user1.setPassword("123456");
            iUserService.updateById(user1);
            return RetResponse.makeOKRsp(RetCode.SUCCESS,user1,"密码已重置为123456，请重新登录！");
        }else{
            return RetResponse.makeErrRsp("用户名输入有误！");
        }
    }

    //添加对象
    @PostMapping("/updateManagerPassword")
    @ApiOperation(value = "修改密码", notes = "修改管理员密码接口",httpMethod = "POST")
    public RetResult updateManagerPassword(String userName,  String password, HttpServletRequest request) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userName",userName);
        queryWrapper.isNull("deleteTime");
        User user1 = userMapper.selectOne(queryWrapper);
        if (user1 != null){
            user1.setPassword(password);
            iUserService.updateById(user1);
            return RetResponse.makeOKRsp(RetCode.SUCCESS,user1,"密码已修改成功，请重新登录！");
        }else{
            return RetResponse.makeErrRsp("用户名输入有误！");
        }
    }

    @ApiOperation(value = "管理员查询所有用户", notes = "查询出所有用户信息,name参数为按照用户名模糊查询用户", httpMethod = "POST")
    @PostMapping("/querybyuserid")
    public RetResult querybyuserid(HttpServletRequest request,@RequestParam(required = false)String name,
                                   @ApiParam(value = "当前页，不传则默认为第一页") @RequestParam(required = false,defaultValue = "1") Integer currentPage,
                                   @ApiParam(value = "每页显示条数，不传默认每页20条") @RequestParam(required = false,defaultValue = "20") Integer size){
        QueryWrapper<User> queryWrapper= Wrappers.<User> query();
        queryWrapper.orderByDesc("createTime");
        queryWrapper.eq("level",0);
        if (name!=null&&name.length()!=0){
            queryWrapper.like("name",name);
        }
        queryWrapper.isNull("deleteTime");
        Page<User> page =userMapper.selectPage(new Page<User>(currentPage,size),queryWrapper);
        return RetResponse.makeOKRsp(page);
    }

    @ApiOperation(value = "管理员查询指定id用户", notes = "管理员查询指定id用户", httpMethod = "POST")
    @PostMapping("/querybyid")
    public RetResult querybyuserid(Integer id,HttpServletRequest request){
        User user = iUserService.queryById(id.toString());
        return RetResponse.makeOKRsp(user);
    }

    @ApiOperation(value = "管理员删除指定id用户", notes = "管理员删除指定id用户", httpMethod = "POST")
    @PostMapping("/deletebyuserid")
    public RetResult deletebyuserid(Integer id,HttpServletRequest request){
        User user=new User();
        user.setId(id);
        user.setDeleteTime(new Date());
        boolean b = iUserService.saveOrUpdate(user);
        if (b){
            return RetResponse.makeOKRsp();
        }
        return RetResponse.makeErrRsp();
    }


}
